<?php

namespace app\api\controller\port;

use app\common\controller\Api;

use think\Exception;
use app\common\model\Order as OrderModel;

/**
 * 订单接口
 * 
 */
class Order extends Api
{

    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new OrderModel();
    }



    /**
     * 下单
     * 
     */
    public function cBancOrder()
    {
        $uid = $this->auth->id;

        $params = input('post.');
        $rule = [
            'banc_id|班次' => 'require|number',
            'type|订单类型' => "require|in:1,2",
            'mobile|手机号' => 'require|regex:/^1[3-9]{1}[0-9]{9}$/',
            'start_station_id|出发站' => "require",
            'end_station_id|终点站' => "require",
        ];
        $message = [
            'mobile.require' => '请填写手机号',
            'mobile.regex' => '手机号格式不正确',
        ];
        //验证规则
        $validate = validate()->rule($rule)->message($message);
        $validate->check($params) || $this->error($validate->getError());

        if($params['type'] == 1){ //拼车
            empty($params['passenger_ids']) && $this->error('请选择乘客');
        }elseif($params['type'] == 2){ //包车
            empty($params['username']) && $this->error('请填写姓名');
            empty($params['idcard']) && $this->error('请填写身份证号');
            $preg = '/^\d{6}(19|2\d)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)?$/';
            preg_match($preg,$params['idcard']) || $this->error('身份证号格式不正确');
        }

        try{
            db()->startTrans();
    
            $order = $this->model->createOrder($uid,$params);
            $order_id = $order->id;
            
            db()->commit();
            $this->success('下单成功',compact('order_id'));
        }catch (Exception $e){
            db()->rollback();
            $this->error($e->getMessage()?:'下单失败');
        }
    }


    /**
     * 订单详情
     * 
     */
    public function orderDetail()
    {
        $order_id = I('post.order_id');
        empty($order_id) && $this->error('订单参数有误');

        $detail = $this->getOrderDetail(['id'=>$order_id,'uid'=>$this->auth->id]);
        $detail->up_car_data = json_decode($detail->up_car_data);
        $detail->down_car_data = json_decode($detail->down_car_data);
        if($detail->qrcode){
            $detail->qrcode = cdnurl($detail->qrcode,true);
        }
        //退款信息
        $refund_data = [];
        if(in_array($detail->status,[4,5,6])){
            $refund_data = db('order_refund')
            ->where('order_id',$detail->id)
            ->field('refund_desc,refund_rate,rate_money,refund_money,create_time')
            ->find();
        }
        $detail->refund_data = $refund_data;
        // 乘客信息
        $passenger = [];
        if($detail->type == 1){
            $passenger = db('passenger')->where('id','in',$detail->passenger_ids)->field('id,name,mobile,idcard')->select();
        }
        $detail->passenger_data = $passenger;
        //退款费率信息
        $refund_rate = config('site.refund_rate');
        $order_pay_price = $detail->pay_price;
        $rate_money = round($order_pay_price * $refund_rate / 100, 2);
        $detail->refund_rate_data = compact('refund_rate','rate_money');

        $this->success('Success',$detail);
    }


    /**
     * 取消订单
     * 
     */
    public function cancelOrder()
    {
        $order_id = I('post.order_id');
        empty($order_id) && $this->error('订单参数有误');
        $uid = $this->auth->id;
        $detail = $this->getOrderDetail(['id'=>$order_id,'uid'=>$uid]);
        $detail->status == 0 || $this->error('当前订单不可取消');

        $ret = $detail->save(['status'=>7]);
        $ret && $this->success('已取消');
        $this->error('操作失败');
    }


    /**
     * 订单支付
     * 
     */
    public function orderPay()
    {
        $order_id = I('post.order_id');
        empty($order_id) && $this->error('订单参数有误');
        $uid = $this->auth->id;
        $detail = $this->getOrderDetail(['id'=>$order_id,'uid'=>$uid]);
        $detail->status == 0 || $this->error('当前订单不可支付');

        $payParams = [
            'amount'=>$detail->pay_price,
            'orderid'=>$detail->order_sn,
            'type'=>"wechat",
            'title'=>$detail->type==1 ? '拼车下单' : '包车下单',
            'method'=>"miniapp",
            'openid'=>$this->auth->openid,
            'notifyurl' => request()->root(true) . "/api/port/notify/wxnotify"
        ];
        $wxret = \addons\epay\library\Service::submitOrder($payParams);
        $wxret = json_decode($wxret,true);

        $this->success('Success',$wxret);
    }


    /**
     * 申请退款
     * 
     */
    public function refundOrder()
    {
        $order_id = I('post.order_id');
        empty($order_id) && $this->error('订单参数有误');
        $refund_desc = I('post.refund_desc');
        empty($refund_desc) && $this->error('请填写退款原因');
        $uid = $this->auth->id;
        $detail = $this->getOrderDetail(['id'=>$order_id,'uid'=>$uid]);
        $detail->status == 1 || $this->error('当前订单不可申请退款');

        try{
            db()->startTrans();
    
            $detail->save(['status'=>4]);

            $refund_rate = config('site.refund_rate');
            $order_pay_price = $detail->pay_price;
            $rate_money = round($order_pay_price * $refund_rate / 100, 2);
            $refund_money = round($order_pay_price - $rate_money, 2);
            $ins_data = [
                'uid'=>$uid,
                'order_id'=>$detail->id,
                'order_sn'=>$detail->order_sn,
                'banc_id'=>$detail->banc_id,
                'order_pay_price'=>$order_pay_price,
                'refund_desc'=>$refund_desc,
                'refund_rate'=>$refund_rate,
                'rate_money'=>$rate_money,
                'refund_money'=>$refund_money
            ];
            db('order_refund')->insert($ins_data);
            
            db()->commit();
            $this->success('申请成功');
        }catch (Exception $e){
            db()->rollback();
            $this->error($e->getMessage()?:'操作失败');
        }
    }


    /**
     * 订单列表
     * 
     */
    public function orderList()
    {
        $status = I('post.status',1);
        $limit = I('post.limit',10);

        $where = ['uid'=>$this->auth->id];
        switch ($status) {
            case 1: //全部
                
                break;
            case 2: //待支付
                $where['status'] = 0;
                break;
            case 3: //已完成
                $where['status'] = 3;
                break;
            case 4: //退款
                $where['status'] = ['in',[4,5,6]];
                break;
            case 5: //当前行程
                $where['status'] = ['in',[1,2]];
                break;
            case 6: //历史行程
                $where['status'] = ['in',[3,4,5,6]];
                break;
            case 7: //可开票
                $where['status'] = 3;
                $where['is_ticket'] = 0;
                break;
            // default:
        }

        $Model = $this->model;
        $Model->where = $where;
        $Model->limit = $limit;
        $Model->fields = 'id,order_sn,type,status,depart_time,start_station,start_station_tags,start_station_coordinate,end_station,end_station_tags,distance,distance_time,qrcode,expirae_time,up_car_data,down_car_data,ticket_price,pay_price';
        $list = $Model->_list();
        $refund_rate = config('site.refund_rate');
        foreach($list['data'] as &$val){
            $val['up_car_data'] = json_decode($val['up_car_data']);
            $val['down_car_data'] = json_decode($val['down_car_data']);
            
            $val['refund_rate'] = $refund_rate;
            $order_pay_price = $val['pay_price'];
            $val['rate_money'] = round($order_pay_price * $refund_rate / 100, 2);
            if($val['qrcode']){
                $val['qrcode'] = cdnurl($val['qrcode'],true);
            }
        }
        $this->success('Success',$list);
    }


    /**
     * 开发票
     * 
     */
    public function makeInvoice()
    {
        $params = I('post.');
        $rule = [
            'order_id|订单参数' => 'require',
            'type|抬头类型' => 'require|in:1,2',
            'invoice|发票抬头' => 'require',
            'details|发票内容' => "require",
            'email|电子邮箱' => "require|email",
        ];
        $message = [];
        //验证规则
        $validate = validate()->rule($rule)->message($message);
        $validate->check($params) || $this->error($validate->getError());
        
        $order_id = $params['order_id'];
        $uid = $this->auth->id;
        $detail = $this->getOrderDetail(['id'=>$order_id,'uid'=>$uid]);
        $detail->status == 3 || $this->error('当前订单不可开发票');
        $detail->is_ticket == 1 && $this->error('当前订单已开发票');

        try{
            db()->startTrans();
    
            $detail->save(['is_ticket'=>1]);

            $ins_data = [
                'uid'=>$uid,
                'order_id'=>$detail->id,
                'type'=>$params['type'],
                'invoice'=>$params['invoice'],
                'details'=>$params['details'],
                'money'=>$detail->pay_price,
                'email'=>$params['email']
            ];
            db('order_invoice')->insert($ins_data);
            
            db()->commit();
            $this->success('申请成功');
        }catch (Exception $e){
            db()->rollback();
            $this->error($e->getMessage()?:'操作失败');
        }

    }


    /**
     * 获取发票列表
     * 
     */
    public function getInvoiceList()
    {
        $limit = I('post.limit');
        $order_invoice = db('order_invoice i')
            ->join('order o','o.id=i.order_id','LEFT')
            ->where('i.uid',$this->auth->id)
            ->field('i.*,o.order_sn')
            ->paginate($limit);
            
        $this->success('Success',$order_invoice);
    }


    //获取订单详情
    private function getOrderDetail($where)
    {
        $Model = $this->model;
        $Model->where = $where;
        $Model->limit = 1;
        $detail = $Model->_list();
        empty($detail) && $this->error('没有找到订单信息');
        return $detail;
    }
 


}
